Page({
    data: {
        name: '',
        password: '',
        noLogin: true
    },
    onLoad() {
        let admin = wx.getStorageSync('admin')
        console.log('本地缓存的登录信息', admin)
        if (admin && admin.name && admin.password) {
            this.loginData(admin.name, admin.password)
        }
    },
    // 获取用户输入的账号
    getName(e) {
        console.log(e.detail.value)
        this.setData({
            name: e.detail.value
        })
    },
    // 获取用户输入的密码
    getPassword(e) {
        console.log(e.detail.value)
        this.setData({
            password: e.detail.value
        })
    },

    //点击按钮登录
    goLogin() {
        let name = this.data.name
        let password = this.data.password
        if (!name) {
            wx.showToast({
                icon: 'error',
                title: '请输入账号',
            })
            return
        }
        if (!password) {
            wx.showToast({
                icon: 'error',
                title: '请输入密码',
            })
            return
        }
        console.log(name)
        console.log(password)
        this.loginData(name, password)
    },
    //执行登录的方法
    loginData(name, password) {
        wx.cloud.database().collection('admin')
            .where({
                name,
                password
            }).get().then(res => {
                console.log('返回的数据', res)
                if (res.data && res.data.length > 0) {
                    console.log('登录成功')
                    // 1. 切换到登录成功后的页面
                    this.setData({
                        noLogin: false
                    })
                    // 2缓存账号密码用于记录登录状态
                    let admin = {}
                    admin.name = name
                    admin.password = password
                    wx.setStorageSync('admin', admin)
                } else {
                    wx.showToast({
                        icon: 'error',
                        title: '账号密码错误',
                    })
                    wx.setStorageSync('admin', null)
                }
            }).catch(res => {
                console.log('请求失败', res)
            })
    },
    loginout() {
        wx.setStorageSync('admin', null)
        this.setData({
            noLogin: true
        })
    },
    goHouchu() {
        wx.navigateTo({
          url: '/pages/adminHouchu/adminHouchu',
        })
    },
    goPaihao() {
        wx.navigateTo({
          url: '/pages/adminPaihao/adminPaihao',
        })
    }
})